package com.clp.protocol.iec104.client.pipeline.state;

import com.clp.protocol.iec104.apdu.asdu.IAsdu;
import com.clp.protocol.iec104.client.InMaster;
import com.clp.protocol.iec104.client.Master;
import com.clp.protocol.iec104.client.MasterIAsduRecver;
import com.clp.protocol.iec104.client.pipeline.MPipelineManager;
import com.clp.protocol.core.pdu.PduRecvCallback;

import java.util.Collection;
import java.util.Vector;

public class MInternalIAsduRecver implements MasterIAsduRecver {
    private final InMaster inMaster;

    // 回调列表
    private final Vector<PduRecvCallback<IAsdu>> frameRecvCallbacks = new Vector<>();

    public MInternalIAsduRecver(InMaster inMaster) {
        this.inMaster = inMaster;
    }

    @Override
    public Master master() {
        return inMaster;
    }

    @Override
    public void addRecvCallback(PduRecvCallback<IAsdu> callback) {
        this.frameRecvCallbacks.add(callback);
    }

    @Override
    public void addRecvCallbacks(Collection<PduRecvCallback<IAsdu>> frameRecvCallbacks) {
        this.frameRecvCallbacks.addAll(frameRecvCallbacks);
    }

    @Override
    public void removeRecvCallback(PduRecvCallback<IAsdu> callback) {
        this.frameRecvCallbacks.remove(callback);
    }

    @Override
    public void removeRecvCallbacks(Collection<PduRecvCallback<IAsdu>> frameRecvCallbacks) {
        this.frameRecvCallbacks.removeAll(frameRecvCallbacks);
    }

    public void handleRecvCallbacks(IAsdu iAsdu) {
        master().executor().execute(() -> {
            try {
                this.frameRecvCallbacks.removeIf(callback -> callback.whenRecv(iAsdu));
            } catch (Exception e) {
                e.printStackTrace();
            }
        });
    }
}
